// pages/index/index.js
Page({
  data: {
    todos: [],
    filters: {
      status: 'ongoing',  // ongoing, completed
      responsible: '',
      month: ''
    },
    userInfo: null,
    months: Array.from({length: 12}, (_, i) => i + 1)
  },

  onLoad: function() {
    const app = getApp();
    this.setData({
      userInfo: app.globalData.userInfo
    });
    this.loadTodos();
  },

  onShow: function() {
    this.loadTodos();
  },

  // 加载待办事项
  loadTodos: function() {
    const app = getApp();
    const todos = app.getTodos(this.data.filters);
    this.setData({ todos });
  },

  // 切换状态筛选
  toggleStatus: function(e) {
    const status = e.currentTarget.dataset.status;
    this.setData({
      'filters.status': status
    });
    this.loadTodos();
  },

  // 设置月份筛选
  setMonth: function(e) {
    const month = e.detail.value;
    this.setData({
      'filters.month': month
    });
    this.loadTodos();
  },

  // 设置负责人筛选
  setResponsible: function(e) {
    const responsible = e.detail.value;
    this.setData({
      'filters.responsible': responsible
    });
    this.loadTodos();
  },

  // 跳转到待办详情
  navigateToDetail: function(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/todo/detail?id=${id}`
    });
  },

  // 添加待办事项
  addTodo: function() {
    wx.navigateTo({
      url: '/pages/todo/detail'
    });
  },

  // 快速完成待办
  completeTodo: function(e) {
    const app = getApp();
    const id = e.currentTarget.dataset.id;
    const todo = this.data.todos.find(t => t.id === id);
    
    // 检查是否为监督人
    if (app.globalData.userInfo.nickName !== todo.supervisor) {
      wx.showToast({
        title: '只有监督人可以确认完成',
        icon: 'none'
      });
      return;
    }

    app.updateTodo(id, {
      status: 'completed',
      actualEndTime: new Date().toISOString()
    });
    this.loadTodos();
  }
}));